import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import DataBase from 'src/config/database';
import { DeleteResult, In, IsNull, Not, Repository } from 'typeorm';
import { AnswerInfo } from '../answerInfo/answerInfo.entity';
import { LikeVideo } from '../likeVideo/likeVideo.entity';
import { MultiImg } from '../multiImg/multiImg.entity';
import { Notices } from '../notices/notices.entity';
import { NoticeCheckEnum, NoticeIsDeleteEnum, NoticeTypeEnum } from '../notices/notices.enum';
import { Platform } from '../platform/platform.entity';
import { Profit } from '../profit/profit.entity';
import { EnumProfitPostAnswer, profitEnum, profitTypeEnum } from '../profit/profit.enum';
import { Reward } from '../reward/reward.entity';
import { payStatusEnum } from '../reward/reward.enum';
import { TraceRelaTable } from '../traceRelaTable/traceRelaTable.entity';
import { Video } from '../video/video.entity';
import { IsRewardEnum, OriginalEnum, OverseasEnum, VideoEnum } from '../video/video.enum';
import { Answer } from './answer.entity';
import { CheckEnum, DeleteTagEnum, RejectReasonEnum } from './answer.enum';
import utils from 'src/common/utils';
import { UserService } from '../user/user.service';
import { User } from '../user/user.entity';
import { question_store_wx_user, system_wx_user } from 'src/setting';
import { Questions } from '../questions/questions.entity';
import { RewardSuccess } from '../rewardSuccess/rewardSuccess.entity';
import { UserSetting } from '../userSetting/userSetting.entity';
import { AnswerIdCard } from '../answerIdCard/answerIdCard.entity';
import { WXAPI } from 'src/common/wx_api';
import { getQueryVideoField, getVideoOtherParams } from 'src/common/sql/video';
import { InternetCelebrityGroup } from '../internetCelebrityGroup/internetCelebrityGroup.entity';
import { EnumInternetCelebrityGroupTypeEnum } from '../internetCelebrityGroup/internetCelebrityGroup.enum';
import { TypeEnum } from '../platform/platform.enum';
import { InternetCelebrity } from '../internetCelebrity/internetCelebrity.entity';
import { EnumInternetCelebrityOverseasEnum } from '../internetCelebrity/internetCelebrity.enum';
import { WsStartGateway } from '../ws/ws.gateway';
import { EnumQuestionPostAnswer } from '../questions/questions.enum';
let WXAPIOBJ = new WXAPI()

@Injectable()
export class AnswerService {
  constructor(
    @InjectRepository(Answer)
    private asRepository: Repository<Answer>,
    @InjectRepository(Platform)
    private platformRepository: Repository<Platform>,
    @InjectRepository(AnswerInfo)
    private answerInfoRepository: Repository<AnswerInfo>,
    @InjectRepository(Video)
    private videoRepository: Repository<Video>,
    @InjectRepository(Notices)
    private noticesRepository: Repository<Notices>,
    @InjectRepository(LikeVideo)
    private likeVideoepository: Repository<LikeVideo>,
    @InjectRepository(MultiImg)
    private multiImgRespository: Repository<MultiImg>,
    @InjectRepository(Reward)
    private rewardRespository: Repository<Reward>,
    @InjectRepository(Profit)
    private profitRespository: Repository<Profit>,
    @InjectRepository(User)
    private userRespository: Repository<User>,
    @InjectRepository(Questions)
    private questionsRespository: Repository<Questions>,
    @InjectRepository(RewardSuccess)
    private rewardSuccessRespository: Repository<RewardSuccess>,
    @InjectRepository(UserSetting)
    private userSettingRespository: Repository<UserSetting>,
    @InjectRepository(AnswerIdCard)
    private answerIdCardRespository: Repository<AnswerIdCard>,
    @InjectRepository(TraceRelaTable)
    private traceRelaTableRespository: Repository<TraceRelaTable>,
    @InjectRepository(InternetCelebrityGroup)
    private internetCelebrityGroupRespository: Repository<InternetCelebrityGroup>,
    @InjectRepository(Platform)
    private platformRespository: Repository<Platform>,
    @InjectRepository(InternetCelebrity)
    private internetCelebrityRespository: Repository<InternetCelebrity>,
    private readonly wsStartGateway: WsStartGateway,
    
    
    
  ) {}


  /**
   * 删除一个视频下某个用户的所有回答
   */
  async deleteByVideoId(video_id: number, wx_user: string): Promise<DeleteResult>{
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try{
      await this.asRepository.createQueryBuilder(null, queryRunner).delete()
        .andWhere("video_id=:video_id",{video_id: video_id})
        .andWhere("wx_user=:wx_user",{wx_user: wx_user})
        .andWhere("(`check` = 0 or `check` is null)",{})
        .execute()
      //设置通知为已经删除的状态
      await this.noticesRepository.createQueryBuilder(null, queryRunner).update({is_delete: NoticeIsDeleteEnum.yes})
        .where({video_id: video_id, wx_user: wx_user}).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  /**
   * 删除已经审核通过的答案
   * @param video_id 
   * @param wx_user 
   * @returns 
   */
  async deleteIsCheckByVideoId(video_id: number, wx_user: string): Promise<string>{
    //查找答案详情
    let findAnswer: Answer = await this.asRepository.findOne({where:{video_id: video_id,wx_user: wx_user, check: CheckEnum.yes}})
    if(!findAnswer){
      return '答案不存在'
    }
    if(findAnswer.wx_user === system_wx_user){
      return
    }
    let answer_id = findAnswer.id

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    delete findAnswer.id
    findAnswer.wx_user = system_wx_user
    findAnswer.create_time = new Date()
    findAnswer.check_time = new Date()
    try {
      let addAnswer: Answer = await queryRunner.manager.save(findAnswer)
      await this.asRepository.createQueryBuilder(null,queryRunner).update({delete_tag: DeleteTagEnum.yes, check: 0}).where({video_id: video_id, wx_user: wx_user}).execute()
      //修改回答详情
      await this.answerInfoRepository.createQueryBuilder(null, queryRunner).update({answer_id: addAnswer.id}).where({answer_id: answer_id}).execute()
      //设置通知为已经删除的状态
      await this.noticesRepository.createQueryBuilder(null, queryRunner).update({is_delete: NoticeIsDeleteEnum.yes})
        .where({video_id: video_id, wx_user: wx_user}).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  
  /**
   * 第一堆答案被拒绝，删除答案
   */
  async deleteAnswerIsReject(video_id: number, wx_user: string): Promise<string>{
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      await this.asRepository.createQueryBuilder(null,queryRunner).update({delete_tag: DeleteTagEnum.yes}).where({video_id: video_id, wx_user: wx_user}).execute()
      //设置通知为已经删除的状态
      await this.noticesRepository.createQueryBuilder(null, queryRunner).update({is_delete: NoticeIsDeleteEnum.yes})
        .where({video_id: video_id, wx_user: wx_user}).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  /**
   * 查询某个用户某个视频的所有回答列表
   * @param wx_user 
   * @param video_id 
   * @returns 
   */
  async find_history_by_video_id(wx_user: string, video_id: number): Promise<{answer:Answer[],answerInfo:AnswerInfo[]}> {
    // let answer:Answer[] = await this.asRepository.find({where:{video_id:video_id,wx_user:wx_user}})
    let answer:Answer[] = await this.asRepository.query(`
      select answer.*,reject_reason.reason as reject_reason_txt from answer 
      left join reject_reason on reject_reason.id = answer.reject_reason
      where answer.video_id = ? and answer.wx_user = ?
    `,[video_id, wx_user])

    //答案详情
    let answerInfo:AnswerInfo[] = await this.answerInfoRepository.query(`
      select a.*,b.check from answer_info a
      inner join answer b on b.id = a.answer_id and b.delete_tag = 0
      where b.video_id = ? and b.wx_user = ? and a.platform != '' and a.platform is not null
    `,[video_id, wx_user])

    answer.map((e:any) => {
      if(utils.judeAnswerIsReject(e)){
        e.answer_reject = true
      }else if(e.check == 1){
        e.answer_accept = true
      }else{
        e.answer_checking = true
      }
    })
    
    return {
      answer,
      answerInfo
    }
  }




  /**
   * 查询视频的答案
   * @param wx_user 
   * @param video_id 
   * @returns 
   */
  async find_answer_by_video_id(wx_user: string, video_id: number, nowVideoIds: any, loadType?: string, main?: boolean): 
    Promise<{relaIcAnswerList: [], user_answer: any[], icGroup: any[], multi_img: MultiImg[], recommendList: any[], answerInfo: any[], recommendMultiImg: any[]}>{
    let recommendList = []
    let notPlatformList = []
    let answerInfoList = []
    let recommendMultiImg = []
    if(main){
      //查询当前作品所属平台
      let workPlatform: any = await this.platformRepository.query(`
        select a.platform, b.type from platform a
        inner join video b on b.ic_group = a.ic_group
        where b.id = ? and a.platform != '' and a.platform is not null
      `,[video_id])
      if(workPlatform.length > 0){
        nowVideoIds = nowVideoIds.filter(e => e)
        let platform = workPlatform[0].platform
        //查询第三堆的平台
        let level3List = await this.userSettingRespository.query(`select * from setting where setting.key = 'level3'`,[])
        //查询同平台视频
        if(level3List.find(e => e.value.toLocaleLowerCase() == platform.toLocaleLowerCase())){
          let videoSql = []
          let answerSql = []
          let answerSqlParams = []
          nowVideoIds.map(e => {
            videoSql.push(`video.id != ?`)
          })
          let videoSqlText = videoSql.join(' and ')
          if(videoSqlText){
            videoSqlText = ` and ${videoSqlText}`
          }
          let workType = utils.getMainWorkType(loadType)
          if(loadType === 'all'){
            let videoType: VideoEnum = workPlatform[0].type
            if(videoType === VideoEnum.video){
              workType = utils.getMainWorkType('image')
            }else{
              workType = utils.getMainWorkType('video')
            }

          }
          let getData = async (wkType) => {
            let { sql, beforeParams, afterParams } = getQueryVideoField(wx_user, `
            (
              select video.*
              from video
              inner join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
              inner join platform on platform.ic_group = internet_celebrity_group.id
              where video.check = 1 and internet_celebrity_group.type = 0 and platform.platform in (select setting.value from setting where setting.key = 'level3')
                and video.ic_group not in (
                  select watch_record_ic.ic_group from watch_record_ic
                  where watch_record_ic.wx_user = ? 
                )
                and video.id not in (
                  select watch_record.video_id from watch_record
                  where watch_record.wx_user = ?
                ) and (video.type = ? or ? = 2) ${videoSqlText}
            ) video
            `)
            return await this.videoRepository.query(`
              select 
              ${sql}
              order by video.create_time desc
              limit 0,1
            `,[...beforeParams, wx_user, wx_user, wkType, wkType, ...nowVideoIds , ...afterParams])
          }
          recommendList = await getData(workType)
          if(recommendList.length === 0 && loadType === 'all'){
            getData(utils.getMainWorkType('all'))
          }
          recommendList.map(e => {
            e.workSource = 'ic'
            e.commend = true
          })


          let ids = recommendList.map(e => e.id)
          let result = await getVideoOtherParams(this.videoRepository, ids, ids, wx_user)
          answerInfoList = result.answerList
          recommendMultiImg = result.multiImg
        }
      }
    }

    const user_answer = await this.asRepository.query(`
      select e.*,a.ic_group,b.id as profit_works,a.type as video_type,b.type as type,b.reject_auto_time
      from answer b
      left join answer_info as e on e.answer_id = b.id
      inner join video a on a.id = b.video_id
      where b.video_id = ? and (b.id in (
        select a.answer_id from profit a where a.use_wx_user = ?
      ) or b.wx_user = ?) and b.check = 1 and b.delete_tag = 0
      order by e.create_time desc
    `,[video_id, wx_user, wx_user])
    
    let icGroup = []
    //如果当前视频是未认证且未通过审核，不查询后台关联的答案
    let findVideo = await this.videoRepository.findOne({where:{id: video_id}})
    //认证作品
    if(findVideo.overseas == OverseasEnum.yes){
      icGroup = await this.platformRepository.query(`
        select distinct a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account from platform a
        inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
        inner join internet_celebrity_group on internet_celebrity_group.id = a.ic_group
        where a.platform != '' and a.platform is not null and internet_celebrity_group.type = 2 and internet_celebrity_group.wx_user = ?
        order by a.id asc
      `,[findVideo.wx_user])
    }else if(!(findVideo.overseas == OverseasEnum.virtual && findVideo.check_text !== 0 && findVideo.check_text !== 1)){
      if(user_answer.length === 0 || user_answer[0].ic_group){
        // 后台关联的答案
        icGroup = await this.platformRepository.query(`
          select distinct a.id as id_platform,a.platform,a.wx_user,b.id as id_ic,b.name as ic_name,b.img,b.img_id,b.avatar_img,b.avatar_id,b.account from platform a
          inner join internet_celebrity b on b.platform = a.id and b.wx_user = a.wx_user
          where a.ic_group in (select ic_group from video where video.id = ?) and a.platform != '' and a.platform is not null
          order by a.id asc
        `,[video_id])
      }
    }

    //如果当前视频的网红关联了真实网红
    let relaIcAnswerList = await this.videoRepository.query(`
      select distinct wx_user.name as ic_name, wx_user.avatar_img, wx_user.id_card,wx_user.id as wx_user_id,
        (
          select count(1) from video as v
          where v.ic_group = internet_celebrity_group_rela_ic_info.ic_group_rela_ic_info and v.profit_type = 1
        ) as count_look_full_video
      from wx_user
      inner join internet_celebrity_group on internet_celebrity_group.wx_user = wx_user.openid
      inner join internet_celebrity_group_rela_ic_info on internet_celebrity_group_rela_ic_info.ic_group_rela_ic_info = internet_celebrity_group.id
      inner join video on video.ic_group = internet_celebrity_group_rela_ic_info.ic_group
      where video.id = ?
    `,[video_id])

    //查询多图
    let multi_img: MultiImg[] = []
    if(user_answer.length > 0 && user_answer[0].video_type === VideoEnum.image){
      multi_img = await this.multiImgRespository.query(`
      select * from multi_img
      where video_id = ?
    `,[video_id])
    }
    return {relaIcAnswerList: relaIcAnswerList, user_answer, icGroup: icGroup, multi_img:multi_img, recommendList: recommendList, answerInfo: answerInfoList, recommendMultiImg: recommendMultiImg}
  }

  getMultiImg(video_id){
    return this.multiImgRespository.query(`
    select * from multi_img
    where video_id = ?
  `,[video_id])
  }

  /**
   * 修改状态：根据回答id
   * @param id 
   */
  async check_by_id(id: number, check: number){
    this.asRepository.update({id:id},{check:check,check_time:new Date()})
  }

  async check(data: Answer){
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    //查询视频/图片
    let findVideo = await this.videoRepository.findOne({where:{id:data.video_id}})
    if(!findVideo){
      return '视频不存在'
    }
    //查询答案详情
    let findAnswer = await this.asRepository.findOne({where:{id:data.id}})
    if(!findVideo){
      return '答案不存在'
    }
    let findReward: Reward
    if(findVideo.isreward == IsRewardEnum.yes){
      findReward = await this.rewardRespository.findOne({where:{video_id:data.video_id}})
      if(!findReward){
        return '悬赏不存在'
      }
    }
    try {
      let noticeList = []
      //提问已有答案
      if(findVideo.original == 0){
        let notice = new Notices()
        notice.create_time = new Date()
        notice.video_id = data.video_id
        notice.check = NoticeCheckEnum.yes
        notice.wx_user = findVideo.wx_user
        notice.type = NoticeTypeEnum.question_is_answer
        noticeList.push(notice)
      }
      //查询当前视频所有收藏的人
      let collectionList = await this.likeVideoepository.find({where:{video_id:data.video_id}})
      collectionList.map(e => {
        let notice = new Notices()
        notice.create_time = new Date()
        notice.video_id = data.video_id
        notice.wx_user = e.wx_user
        notice.check = NoticeCheckEnum.yes
        notice.type = NoticeTypeEnum.collection_is_answer
        noticeList.push(notice)
      })

      //你的回答被采纳
      let notice = new Notices()
      notice.create_time = new Date()
      notice.video_id = data.video_id
      notice.wx_user = findAnswer.wx_user
      notice.check = NoticeCheckEnum.yes
      notice.type = NoticeTypeEnum.answer_accept
      noticeList.push(notice)

      //保存通知
      await this.noticesRepository.createQueryBuilder(null,queryRunner)
        .insert()
        .into(Notices)
        .values(noticeList)
        .execute()
        

      //修改当前答案视频其他答案审核状态为未通过
      await this.asRepository.createQueryBuilder(null,queryRunner).update({check:0,check_time:new Date()}).where({video_id:data.video_id,id:Not(data.id)}).execute()
      //修改当前答案审核状态为通过
      await queryRunner.manager.save(data)
      //修改悬赏状态
      if(findVideo.isreward == IsRewardEnum.yes && findReward){
        //查找悬赏
        await this.rewardRespository.createQueryBuilder(null,queryRunner).update({pay_status: payStatusEnum.used}).where({video_id:findVideo.id}).execute()
        //添加收益表
        let profit = new Profit()
        profit.answer_id = data.id
        profit.author_wx_user = findAnswer.wx_user
        profit.use_wx_user = findReward.wx_user
        profit.status = profitEnum.entry
        profit.create_time = new Date()
        profit.update_time = new Date()
        profit.unit_price = findReward.unit_price
        profit.service_charge = findReward.service_charge
        profit.type = profitTypeEnum.reward
        await this.profitRespository.createQueryBuilder(null, queryRunner).insert().into(Profit).values(profit).execute()
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  /**
   * 查询所有答案
   * @param skip 
   * @param take 
   * @returns 
   */
  async findAll_Check(skip: number, take: number, keyword: string, searchType: string | number): Promise<{data:any[],total:number,answerInfo:any[]}> {
    if(searchType === ''){
      searchType = ''
    }else if(searchType == 0){
      searchType = 0
    }else if(searchType == 1){
      searchType = 1
    }else{
      searchType = ''
    }
    let dataList = []
    let answerInfoList = []
    let total = []
    if(searchType === ''){
      dataList = await this.asRepository.query(`
        select b.*,a.id as video_id,a.video_url,a.video_cover,a.type,(select answer.check from answer where answer.video_id = a.id and answer.check = 1 limit 1) as ic_check from video a 
        inner join answer b on b.video_id = a.id and b.delete_tag = 0
        where a.profit_type = 0 and b.check is null and b.video_id not in (
          select answer.video_id from answer 
          where answer.video_id = a.id and answer.check = 1 and answer.delete_tag = 0
        ) and b.video_id like ?
        order by b.create_time desc
        limit ?,?
      `,[`%${keyword}%`, skip, take])
      
      answerInfoList = await this.asRepository.query(`
        select a.* from answer_info a
        inner join answer b on b.id = a.answer_id and b.delete_tag = 0
        inner join (
          select a.id from video a 
          inner join answer b on b.video_id = a.id and b.delete_tag = 0
          where a.profit_type = 0 and b.check is null and b.video_id not in (
            select answer.video_id from answer 
            where answer.video_id = a.id and answer.check = 1 and answer.delete_tag = 0
          ) and b.video_id like ?
          order by b.create_time desc
          limit ?,?
        ) as c on c.id = b.video_id
        order by a.id desc
      `,[`%${keyword}%`, skip, take])

      total = await this.asRepository.query(`
        select count(1) total from video a 
        inner join answer b on b.video_id = a.id and b.delete_tag = 0
        where a.profit_type = 0 and b.check is null
      `,[])
    }else{
      dataList = await this.asRepository.query(`
        select b.*,a.id as video_id,a.video_url,a.video_cover,a.type,(select answer.check from answer where answer.video_id = a.id and answer.check = 1 limit 1) as ic_check from video a 
        inner join answer b on b.video_id = a.id and b.delete_tag = 0
        where a.profit_type = 0 and b.check = ? and b.video_id like ?
        order by b.create_time desc
        limit ?,?
      `,[searchType, `%${keyword}%`, skip, take])

      answerInfoList = await this.asRepository.query(`
        select a.* from answer_info a
        inner join answer b on b.id = a.answer_id and b.delete_tag = 0
        inner join (
          select a.id 
          from video a 
          inner join answer b on b.video_id = a.id
          where a.profit_type = 0 and b.check = ? and b.video_id like ? and b.delete_tag = 0
          order by b.create_time desc
          limit ?,?
        ) as c on c.id = b.video_id
        order by a.id desc
      `,[searchType, `%${keyword}%`, skip, take])

      total = await this.asRepository.query(`
        select count(1) total from video a 
        inner join answer b on b.video_id = a.id and b.delete_tag = 0
        where a.profit_type = 0 and b.check = ?
      `,[searchType])
    }
    
    return {data:dataList,total:Number(total[0].total), answerInfo:answerInfoList}
  }

  find_By_Video(video_id: number, wx_user: string): Promise<Answer[]> {
    return this.asRepository.query(`
      select a.* from answer a
      where a.video_id = ? and a.wx_user = ? and a.check = 1 and a.delete_tag = 0
    `,[video_id, wx_user])
  }

  findOne_By_wx_user_key(id: number): Promise<Answer> {
    return this.asRepository.findOne({where:{id}});
  }

  /**
   * 查询某个人的所有视频答案和答案对应收益
   * @param wx_user
   * @returns
   */
  findListAndProfit_By_User_Key(wx_user: string): Promise<Answer> {
    return this.asRepository.query(`
      select a.*,b.* from answer a
      inner join video c on c.id = a.video_id
      left join profit b on b.answer_id = a.id
      where a.wx_user = ?
    `,[wx_user])
  }

  findList_By_wx_user_key(wx_user: string): Promise<Answer> {
    return this.asRepository.query(`
      select vi.video_key,ans.answer,ans.check,vi.type,vi.id from video as vi
      inner join answer as ans on ans.video_id = vi.id
      where ans.wx_user = ? and (ans.check = 1 or ans.check is null)
      order by vi.type,vi.id asc
    `,[wx_user])
  }

  findAll(): Promise<Answer[]> {
    return this.asRepository.find();
  }

  findOne(id: number): Promise<Answer> {
    return this.asRepository.findOne({where:{id}});
  }

  async create(wxUser: Answer): Promise<Answer> {
    return await this.asRepository.save(wxUser);
  }

  async answerCreate(video_id: number, wx_user: string, findPlatformList: [], traceRelaTableList: TraceRelaTable[], delete_question?: boolean, answerList?: any): Promise<Answer> {
    let findReward
    let findAnswer
    //查找悬赏
    if(delete_question){
      findReward = await this.rewardSuccessRespository.query(`
        select * from reward_success 
        where reward_success.video_id not in (
          select answer.video_id from profit
          inner join answer on answer.id = profit.answer_id
          where answer.check = 1 and answer.video_id = ? and profit.use_wx_user = ?
        ) and reward_success.video_id = ? and reward_success.wx_user = ?
      `,[video_id, wx_user, video_id, wx_user])
      findReward = findReward[0]
      findAnswer = await this.asRepository.findOne({where:{video_id: video_id, check: CheckEnum.yes}})
    }
    
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    let saveAnswer
    try {
      //删除用户的同提问
      if(delete_question){
        await this.questionsRespository.createQueryBuilder(null, queryRunner).delete().where({video_id: video_id, wx_user: wx_user}).execute()
        if(findReward){
          //退款
          //修改状态为已退款
          await this.rewardRespository.createQueryBuilder(null,queryRunner)
            .update({pay_status:payStatusEnum.reject})
            .where({pay_order: findReward.pay_order, wx_user: wx_user})
            .execute()
          await this.rewardSuccessRespository.createQueryBuilder(null,queryRunner)
            .delete()
            .where({video_id:findReward.video_id, wx_user: wx_user})
            .execute()

          //删除收益表
          if(findAnswer){
            await this.profitRespository.createQueryBuilder(null, queryRunner).delete().where({answer_id: findAnswer.id, use_wx_user: wx_user, status: profitEnum.entry}).execute()
          }
          await WXAPIOBJ.clearPayWallet(wx_user)
        }
      }
      //添加一个回答
      let addAnswer = new Answer()
      addAnswer.video_id = video_id
      addAnswer.wx_user = wx_user
      addAnswer.create_time = new Date()
      addAnswer.update_time = new Date()
      //查询当前视频是否是第二堆视频
      let isLibVideo = await this.videoRepository.query(`
        select v.id from video as v
        inner join platform on platform.ic_group = v.ic_group
        inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
        where internet_celebrity_group.type = 0 
          and (select count(1) from platform as pf where pf.ic_group = v.ic_group and pf.platform in (select setting.value from setting where setting.key = 'level3')) = 0
          and v.id = ? and (v.source = 2 or v.original = 0)
      `,[video_id])
      if(isLibVideo.length > 0){
        //生成随机拒绝时间
        let reject_auto_time = new Date()
        reject_auto_time.setMinutes(reject_auto_time.getMinutes() + 1)
        addAnswer.reject_auto_time = reject_auto_time
        //查询已找到答案的驳回原因id
          let findFindIsFind = await this.asRepository.query(`
          select reject_reason.id from reject_reason
          where reject_reason.key = 'answer_is_find'
        `,[])
        if(findFindIsFind.length === 0){
          throw new Error('找不到驳回原因 answer_is_find 请添加')
        }
        addAnswer.reject_reason = findFindIsFind[0].id
      }

      //获取当前用户的回答id
      let findAnswerIdCard = await this.answerIdCardRespository.findOne({where:{wx_user: wx_user, video_id: video_id}})
      addAnswer.id_card = 1 
      if(findAnswerIdCard){
        addAnswer.id_card = findAnswerIdCard.id_card
      }else{
        let answerIdCard = new AnswerIdCard()
        answerIdCard.wx_user = wx_user
        answerIdCard.video_id = video_id
        answerIdCard.id_card = addAnswer.id_card
        //查找最大id_card
        let maxIdCard = await this.answerIdCardRespository.query(`select max(id_card) as id_card from answer_id_card where wx_user = ?`,[wx_user])
        if(maxIdCard.length > 0){
          answerIdCard.id_card = (maxIdCard[0].id_card || 0) + 1
        }
        await this.answerIdCardRespository.createQueryBuilder(null, queryRunner).insert().into(AnswerIdCard).values(answerIdCard).execute()
        addAnswer.id_card = answerIdCard.id_card
      }

      saveAnswer = await queryRunner.manager.save(addAnswer);
      let answer_id = saveAnswer.id

      let addAnswerInfoList = []
      answerList.map(e => {
        let addAnswerInfo = new AnswerInfo()
        addAnswerInfo.answer_id = answer_id
        addAnswerInfo.create_time = new Date()
        addAnswerInfo.ic_name = e.ic.name
        addAnswerInfo.img = e.ic.img
        addAnswerInfo.img_id = e.ic.img_id
        addAnswerInfo.platform = e.platform.platform
        addAnswerInfo.video_id = video_id
        addAnswerInfo.trace_id = e.trace_id
        addAnswerInfo.account = e.ic.account
        addAnswerInfo.avatar_id = e.ic.avatar_id
        addAnswerInfo.avatar_img = e.ic.avatar_img
        addAnswerInfoList.push(addAnswerInfo)
      })

      await this.answerInfoRepository.createQueryBuilder(null, queryRunner).insert().into(AnswerInfo).values(addAnswerInfoList).execute()

      traceRelaTableList.map((e:TraceRelaTable) => {
        e.create_time = new Date()
      })
      await this.traceRelaTableRespository.createQueryBuilder(null, queryRunner).insert().into(TraceRelaTable).values(traceRelaTableList).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
      return saveAnswer
    } catch (err) {
      console.log(err,'error')
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async answerUpdate(video_id: number, wx_user: string, findPlatformList: [], traceRelaTableList: TraceRelaTable[], answer_id: number, answerList: any): Promise<{wx_user: string}> {
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let updateAnswerParams: any = {update_time: new Date()}
      //查询当前视频是否是第二堆视频
      let isLibVideo = await this.videoRepository.query(`
        select v.id from video as v
        inner join platform on platform.ic_group = v.ic_group
        inner join internet_celebrity_group on internet_celebrity_group.id = v.ic_group
        where internet_celebrity_group.type = 0 
          and (select count(1) from platform as pf where pf.ic_group = v.ic_group and pf.platform in (select setting.value from setting where setting.key = 'level3')) = 0
          and v.id = ? and (v.source = 2 or v.original = 0)
      `,[video_id])
      if(isLibVideo.length > 0){
        //生成随机拒绝时间
        let reject_auto_time = new Date()
        reject_auto_time.setMinutes(reject_auto_time.getMinutes() + 1)
        updateAnswerParams.reject_auto_time = reject_auto_time
      }
      await this.asRepository.createQueryBuilder(null,queryRunner).update(updateAnswerParams).where({id: answer_id}).execute()
      //删除原有答案
      await this.answerInfoRepository.createQueryBuilder(null, queryRunner).delete().where({answer_id: answer_id}).execute()
      //添加回答详情
      let addAnswerInfoList = []
      answerList.map(async e => {
        let addAnswerInfo = new AnswerInfo()
        addAnswerInfo.answer_id = answer_id
        addAnswerInfo.create_time = new Date()
        addAnswerInfo.ic_name = e.ic.name
        addAnswerInfo.img = e.ic.img
        addAnswerInfo.img_id = e.ic.img_id
        addAnswerInfo.platform = e.platform.platform
        addAnswerInfo.video_id = video_id
        addAnswerInfo.trace_id = e.trace_id
        addAnswerInfo.account = e.ic.account
        addAnswerInfo.avatar_id = e.ic.avatar_id
        addAnswerInfo.avatar_img = e.ic.avatar_img
        addAnswerInfoList.push(addAnswerInfo)
      })
      await this.answerInfoRepository.createQueryBuilder(null, queryRunner).insert().into(AnswerInfo).values(addAnswerInfoList).execute()
      traceRelaTableList.map(e => {
        e.create_time = new Date()
      })
      await this.traceRelaTableRespository.createQueryBuilder(null, queryRunner).insert().into(TraceRelaTable).values(traceRelaTableList).execute()
     
      await queryRunner.commitTransaction()
      await queryRunner.release();
      return {wx_user: wx_user}
    } catch (err) {
      console.log(err,'error11')
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async update(data: Answer): Promise<any> {

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    //查询视频/图片
    let findAnswer = await this.asRepository.findOne({where:{id:data.id}})
    if(!findAnswer){
      return '答案不存在'
    }
    try {
      let noticeList = []
      //你的回答被拒绝
      let notice = new Notices()
      notice.create_time = new Date()
      notice.video_id = data.video_id
      notice.wx_user = findAnswer.wx_user
      notice.check = NoticeCheckEnum.no
      notice.type = NoticeTypeEnum.answer_reject
      noticeList.push(notice)

      //保存通知
      await this.noticesRepository.createQueryBuilder(null,queryRunner)
        .insert()
        .into(Notices)
        .values(noticeList)
        .execute()
        
      //修改当前答案审核状态为未通过
      await queryRunner.manager.save(data)
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }


    // return await this.asRepository.save(wxUser);
  }

  async findAll_By_Question(skip: number, limit: number, video_id: number): Promise<{dataList: Answer[], total: number}> {
    //查询通过的答案
    let checkAnswer = await this.asRepository.findOne({where:{video_id: video_id, check: 1}})
    //查询视频
    let video = await this.videoRepository.findOne({where:{id: video_id}})
    //查找作者填写的
    let authorAnswer
    //视频是虚拟网红
    if(video.overseas === OverseasEnum.virtual && video.original === OriginalEnum.yes){
      authorAnswer = await this.asRepository.query(`
      select answer.id as answer_id, answer_info.platform as info_platform,answer_info.account as info_account,answer_info.ic_name as info_ic_name,answer_info.avatar_img as info_avatar_img, answer_info.img as info_img,
        platform.platform as ic_platform,internet_celebrity.account as ic_account,internet_celebrity.name as ic_name,internet_celebrity.avatar_img as ic_avatar_img, internet_celebrity.img as ic_img,
        answer.check,video.ic_group
      from answer
      left join answer_info on answer_info.answer_id = answer.id
      inner join video on video.id = answer.video_id
      left join internet_celebrity_group on internet_celebrity_group.id = video.ic_group
      left join platform on platform.ic_group = internet_celebrity_group.id
      left join internet_celebrity on internet_celebrity.ic_group = internet_celebrity_group.id
      where video.id = ? and (answer.wx_user = video.wx_user or answer.wx_user = video.wx_user_source)
    `,[video_id])
    }else{
      //查找作者填写的
      authorAnswer = await this.asRepository.query(`
        select DISTINCT a.*, answer.check, answer.check_time from (
          select (select answer.id from answer inner join video on video.id = answer.video_id where video.id = ? 
            and ((video.wx_user_source is null and video.wx_user = answer.wx_user) or (video.wx_user_source is not null and video.wx_user_source = answer.wx_user))
            limit 0,1)  as answer_id,
              platform.platform,internet_celebrity.name, internet_celebrity.account, internet_celebrity.avatar_img, internet_celebrity.create_time
            from internet_celebrity
            inner join platform on platform.id = internet_celebrity.platform and platform.platform is not null and platform.platform != ''
            where internet_celebrity.ic_group in (
              select ic_group from video
              where id = ?
            )
          )a
        inner join answer on answer.id = a.answer_id
      `,[video_id, video_id])
    }

    if(authorAnswer.length > 0){
      limit = limit - 1
      if(video.overseas === OverseasEnum.virtual){
        authorAnswer.map(e => {
          if(e.ic_group){
            e.platform = e.ic_platform
            e.account = e.ic_account
            e.ic_name = e.ic_name
            e.avatar_img = e.ic_avatar_img
            e.img = e.ic_img
          }else{
            e.platform = e.info_platform
            e.account = e.info_account
            e.ic_name = e.info_ic_name
            e.avatar_img = e.info_avatar_img
            e.img = e.info_img
          }
        })
      }

    }
    //查找别人回答的
    let otherAnswer = await this.asRepository.query(`
      select answer_info.*,b.check,b.check_time,b.ic_group from answer_info
      inner join answer b on b.id = answer_info.answer_id
      where answer_info.answer_id in (
        select answer.id from answer
        inner join video on video.id = answer.video_id
        where answer.video_id = ? and answer.type = 0 and ((video.wx_user_source is not null && answer.wx_user != video.wx_user_source) or (video.wx_user_source is null and answer.wx_user != video.wx_user))
      )
      limit ?,?
    `,[video_id, skip, limit])

    //查找别人回答的（有关联）
    let otherAnswerYesRela = await this.asRepository.query(`
      select b.ic_group,b.id as answer_id,
      platform.platform,internet_celebrity.name, internet_celebrity.account, internet_celebrity.avatar_img, internet_celebrity.img, internet_celebrity.create_time
      from answer_info
      inner join answer b on b.id = answer_info.answer_id
      inner join internet_celebrity on internet_celebrity.ic_group = b.ic_group
      inner join platform on platform.id = internet_celebrity.platform
      where answer_info.answer_id in (
        select answer.id from answer
        inner join video on video.id = answer.video_id
        where answer.video_id = ? and answer.type = 0 and ((video.wx_user_source is not null && answer.wx_user != video.wx_user_source) or (video.wx_user_source is null and answer.wx_user != video.wx_user))
      ) and b.ic_group is not null
    `,[video_id])

    let answerIdList = [...new Set([...otherAnswerYesRela.map(e => e.answer_id)])]
    answerIdList.filter(e => otherAnswer.find(c => c.answer_id == e)).map(e => {
      otherAnswer = otherAnswer.filter(c => c.answer_id != e)
      otherAnswer.push(...otherAnswerYesRela.filter(c => c.answer_id == e))
    })
    otherAnswer.sort((a,b) => a.answer_id - b.answer_id)

    

    let list = []
    otherAnswer.map(e => {
      let item = {
        answer_id: e.answer_id,
        platform: e.platform,
        ic_name: e.ic_name || e.name,
        account: e.account,
        create_time: e.create_time,
        avatar_img: e.avatar_img,
        check: utils.judeAnswerIsReject(e) ? false : undefined,
        check_time: e.check_time,
        img: e.img
      }
      list.push(item)
    })
    if((checkAnswer && checkAnswer.wx_user == video.wx_user) || !checkAnswer){
      authorAnswer.map(c => { 
        let item = {
          answer_id: c.answer_id,
          platform: c.platform,
          ic_name: c.ic_name || c.name,
          account: c.account,
          create_time: c.create_time,
          avatar_img: c.avatar_img,
          check: utils.judeAnswerIsReject(c) ? false : undefined,
          check_time: c.check_time,
          img: c.img
        }
        list.push(item)
      })
    }else if(checkAnswer && authorAnswer.length > 0){
      let findCheckAnswer = list.find(e => e.answer_id == checkAnswer.id)
      console.log(findCheckAnswer, authorAnswer)
      if(findCheckAnswer){
        authorAnswer = authorAnswer[0]
        findCheckAnswer.platform = authorAnswer.platform
        findCheckAnswer.ic_name = authorAnswer.ic_name || authorAnswer.name
        findCheckAnswer.account = authorAnswer.account
        findCheckAnswer.avatar_img = authorAnswer.avatar_img
        findCheckAnswer.img = authorAnswer.img
     
      }
    }
    if(checkAnswer && video?.check){
      list.filter(e => e.answer_id == checkAnswer.id).map(e => {
        e.check = true
      })
    }

    let sumCount = await this.asRepository.countBy({video_id: video_id})
    console.log(sumCount, 'sumcpint')
    return {dataList: list, total: sumCount}
  }

  async remove(id: number): Promise<void> {
    await this.asRepository.delete(id);
  }

  async findById(id: number): Promise<Answer> {
    let result = await this.asRepository.query(`
      select a.*,case when a.answer is null then b.content else a.answer end answer from answer a
      left join answer_template as b on b.id = a.answer_template_id
      where a.id = ?
    `,[id])
    if(result.length > 0){
      return result[0]
    }else{
      return undefined
    }
    // return this.asRepository.findOne({where:{id}});
  }

  async getIDCard(){
    let id = ''
    let loop = async () => {
      id = utils.randomNumberID(7)
      if(await this.internetCelebrityGroupRespository.findOne({where:{id_card: id}})){
        loop()
      }
    }
    await loop()
    return id
  }

  /**
   * 创建网红
   * @param answer_id 
   * @returns 
   */
  async createAnswerIc(answer_id: number){
    //查询答案详情
    let findAnswer = await this.asRepository.findOne({where:{id:answer_id}})
    if(!findAnswer){
      return '答案不存在'
    }
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let ic_group = findAnswer.ic_group
      if(!findAnswer.ic_group){
        let wx_user = system_wx_user
        //查询视频的答案
        let answerInfo: AnswerInfo = await this.answerInfoRepository.findOne({where:{answer_id: answer_id}})
        let platformList = [
          {
            ic:{
              name: answerInfo.ic_name,
              img: answerInfo.img,
              img_id: answerInfo.img_id,
              avatar_id: answerInfo.avatar_id,
              avatar_img: answerInfo.avatar_img,
              account: answerInfo.account
            },
            platform:{
              platform: answerInfo.platform,

            }
          }
        ]
        console.log(answerInfo,'answerInfoanswerInfo')

        let icGroupItem = new InternetCelebrityGroup()
        let first_name = platformList.find(e => e.ic?.name)
        let ic_group_name = ''
        if(first_name){
          ic_group_name = first_name.ic.name
          //除tk ins，其他平台不可重名
          //查询第三堆的平台
          let level3List = await this.userSettingRespository.query(`select * from setting where setting.key = 'level3'`,[])
          //查询同平台视频
          if(!level3List.find(e => e.value.toLocaleLowerCase() == first_name.platform.platform.toLocaleLowerCase())){
            if(await this.internetCelebrityGroupRespository.findOne({where:{name: ic_group_name}})){
              throw new Error('网红已存在，请更换名字。')
            }
          }
        }
        
        icGroupItem.wx_user = wx_user
        icGroupItem.create_time = new Date()
        icGroupItem.name = ic_group_name
        icGroupItem.id_card = await this.getIDCard()
        icGroupItem.type = EnumInternetCelebrityGroupTypeEnum.common
        let addIcGroup = await this.internetCelebrityGroupRespository.createQueryBuilder(null, queryRunner).insert().into(InternetCelebrityGroup).values(icGroupItem).execute()
        ic_group = addIcGroup.identifiers[0].id

        console.log(ic_group,addIcGroup,icGroupItem)


        let e: any = platformList[0]
        let platformItem = new Platform()
        platformItem.platform = e.platform.platform
        platformItem.wx_user = wx_user
        platformItem.type = TypeEnum.virtual
        platformItem.create_time = new Date()
        platformItem.ic_group = ic_group
        let addPlatform = await this.platformRespository.createQueryBuilder(null, queryRunner).insert().into(Platform).values(platformItem).execute()
        let platformId = addPlatform.identifiers[0].id
      
        let icItem = new InternetCelebrity()
        icItem.img = e.ic.img
        icItem.img_id = e.ic.img_id
        icItem.name = e.ic.name
        icItem.avatar_id = e.ic.avatar_id
        icItem.avatar_img = e.ic.avatar_img
        icItem.account = e.ic.account
      
        icItem.platform = platformId
        icItem.ic_group = ic_group
        icItem.wx_user = wx_user
        icItem.overseas = EnumInternetCelebrityOverseasEnum.virtual
        icItem.create_time = new Date()
        //添加网红
        await this.internetCelebrityRespository.createQueryBuilder(null, queryRunner).insert().into(InternetCelebrity).values(icItem).execute()
      }else{
        throw new Error('网红已创建')
      }
      await queryRunner.commitTransaction()
      await queryRunner.release();
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }
  
  /**
   * 答案审核通过
   * @param answer_id 
   * @param ic_group 
   * @param user_token 
   * @returns 
   */
  async CheckAnswer(answer_id: number, user_token: number): Promise<any> {
    let findWxUser = await this.userRespository.findOne({where:{id: user_token}});
    if(!findWxUser){
      return '用户不存在'
    }
    //查询答案详情
    let findAnswer = await this.asRepository.findOne({where:{id:answer_id}})
    if(!findAnswer){
      return '答案不存在'
    }
    //通过审核的答案
    let findYesAnswer:Answer = await this.asRepository.findOne({where:{id:answer_id, check: CheckEnum.yes}})
    let video_id: number = findAnswer.video_id
    //查询视频/图片
    let findVideo = await this.videoRepository.findOne({where:{id:video_id}})
    if(!findVideo){
      return '视频不存在'
    }
    let findRewards: RewardSuccess[]
    if(findVideo.isreward == IsRewardEnum.yes){
      findRewards = await this.rewardSuccessRespository.find({where:{video_id:video_id}})
      // if(findRewards.length === 0){
      //   return '悬赏不存在'
      // }
    }

    //查询所有回答当前视频，并且还未审核的答案
    let notCheckAnswerList = await this.asRepository.query(`
      select * from answer
      where answer.check is null and answer.video_id = ? and answer.id != ?
    `,[video_id, answer_id])

    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let noticeList = []
      //查询当前提问已有的答案
      let isNotice = await this.noticesRepository.find({where:{
        video_id: video_id, 
        check: NoticeCheckEnum.yes, 
        answer_id: answer_id
      }})
      

      //你的回答被采纳
      //查询我的回答被采纳是否有过通知
      console.log(isNotice,' isnotice')
      if(!isNotice.find(e => e.type === NoticeTypeEnum.answer_accept && e.wx_user === findAnswer.wx_user)){
        let notice = new Notices()
        notice.create_time = new Date()
        notice.video_id = video_id
        notice.wx_user = findAnswer.wx_user
        notice.check = NoticeCheckEnum.yes
        notice.type = NoticeTypeEnum.answer_accept
        notice.answer_id = answer_id
        noticeList.push(notice)
      }

      //查询回答是否关联网红
      let ic_group = findAnswer.ic_group
      if(!findAnswer.ic_group){
        throw new Error('没有关联网红。')
      }
      
      //作品是提问，通过审核把作品的所属权转移到提问仓库用户
      let updateVideoParams:any = { ic_group: ic_group, check: 1 }
      let questionList:any = []
      if(findVideo.original === 0){
        let nowTime = new Date()
        if(findVideo.wx_user != question_store_wx_user){
          updateVideoParams.wx_user_source = findVideo.wx_user
          updateVideoParams.wx_user = question_store_wx_user
        }
        //提问答案发货
        await this.questionsRespository.createQueryBuilder(null,queryRunner).update({answer_time: nowTime, post_answer: EnumQuestionPostAnswer.yes}).where({video_id: findVideo.id}).execute()
        
        //查询当前视频所有同提问的人
        questionList = await this.questionsRespository.query(`
          select * from questions
          where questions.video_id = ? and questions.video_id not in (
            select questions.video_id from questions
            inner join notices on notices.video_id = questions.video_id
            where notices.check = ? and notices.type = ? and notices.answer_id = ?
          )
        `,[video_id, NoticeCheckEnum.yes, NoticeTypeEnum.question_is_answer, answer_id])
        questionList.map(e => {
          let notice = new Notices()
          notice.create_time = new Date()
          notice.video_id = video_id
          notice.wx_user = e.wx_user
          notice.check = NoticeCheckEnum.yes
          notice.type = NoticeTypeEnum.question_is_answer
          notice.answer_id = answer_id
          noticeList.push(notice)
        })
      }

      //提问已有答案
      if(findVideo.original == 0){
        //查询当前提问是否有通知
        if(!isNotice.find(e => e.type === NoticeTypeEnum.question_is_answer && e.wx_user === findVideo.wx_user)){
          let notice = new Notices()
          notice.create_time = new Date()
          notice.video_id = video_id
          notice.check = NoticeCheckEnum.yes
          notice.wx_user = findVideo.wx_user
          notice.type = NoticeTypeEnum.question_is_answer
          notice.answer_id = answer_id
          if(!noticeList.find(e => e.video_id == notice.video_id && e.check == notice.check 
            && e.wx_user === notice.wx_user && e.type === notice.type && e.answer_id == notice.answer_id)){
              noticeList.push(notice)
          }
        }
      }

      //查询已找到答案的驳回原因id
      let findFindIsFind = await this.asRepository.query(`
        select reject_reason.id from reject_reason
        where reject_reason.key = 'answer_is_find'
      `,[])
      if(findFindIsFind.length === 0){
        throw new Error('找不到驳回原因 answer_is_find，请添加')
      }
      let reject_reason = findFindIsFind[0].id

      //通知当前视频其他未审核的人
      notCheckAnswerList.map(e => {
        let notice = new Notices()
        notice.create_time = new Date()
        notice.video_id = video_id
        notice.wx_user = e.wx_user
        notice.check = NoticeCheckEnum.no
        notice.type = NoticeTypeEnum.answer_reject
        notice.answer_id = answer_id
        notice.reject_reason = reject_reason
        noticeList.push(notice)
      })

      //保存通知
      if(noticeList.length > 0){
        await this.noticesRepository.createQueryBuilder(null,queryRunner)
        .insert()
        .into(Notices)
        .values(noticeList)
        .execute()
      }

     

      //修改当前答案视频其他答案审核状态为未通过
      await this.asRepository.createQueryBuilder(null,queryRunner)
        .update({check:0,check_time:new Date(), ic_group: null, reject_reason: reject_reason})
        .where({video_id:video_id,id:Not(answer_id), check: IsNull()}).execute()
      
      //修改当前答案审核状态为通过，并且关联网红
      await this.asRepository.createQueryBuilder(null,queryRunner).update({check:1,check_time:new Date(), ic_group: ic_group})
        .where({id: answer_id}).execute()

      //视频关联网红
      await this.videoRepository.createQueryBuilder(null,queryRunner)
        .update(updateVideoParams)
        .where({ id: video_id}).execute()

      //修改悬赏状态
      if(findRewards?.length > 0){
        //如果答案是追加悬赏的人，把悬赏退回
        let outUserReward = findRewards.find(e => e.wx_user == findAnswer.wx_user)
        if(outUserReward){
          await this.rewardRespository.createQueryBuilder(null,queryRunner).update({pay_status: payStatusEnum.reject})
            .where({video_id:findVideo.id, wx_user:outUserReward.wx_user }).execute()
          
            outUserReward.unit_price = 0
            outUserReward.service_charge = 0
          await this.rewardSuccessRespository.createQueryBuilder(null,queryRunner).delete().where({video_id: findVideo.id, wx_user: outUserReward.wx_user}).execute()
        }

        //修改悬赏
        await this.rewardRespository.createQueryBuilder(null,queryRunner).update({pay_status: payStatusEnum.used}).where({video_id:findVideo.id, pay_status: Not(payStatusEnum.reject)}).execute()
        //删除原有收益
        if(findYesAnswer){
          console.log(findYesAnswer,'findYesAnswer', answer_id)
          await this.profitRespository.createQueryBuilder(null,queryRunner).delete().where({
            answer_id: answer_id,
            author_wx_user:findYesAnswer.wx_user,
          }).execute()
        }
        let rewardUsers = [...new Set([...findRewards.map(e => e.wx_user)])]
        let profitList:Profit[] = []
        rewardUsers.map(rewarduser => {
          let unitPriceTotal = findRewards.filter(c => c.wx_user == rewarduser).map(c => Number(c.unit_price||0) - Number(c.service_charge||0)).reduce((sum, current) => sum + current, 0)
          let serviceChargeTotal = findRewards.filter(c => c.wx_user == rewarduser).map(c => Number(c.service_charge||0)).reduce((sum, current) => sum + current, 0)
          //添加收益表
          let profit = new Profit()
          profit.answer_id = answer_id
          profit.author_wx_user = findAnswer.wx_user
          profit.use_wx_user = rewarduser
          profit.status = profitEnum.entry
          profit.create_time = new Date()
          profit.update_time = new Date()
          profit.unit_price = unitPriceTotal
          profit.service_charge = serviceChargeTotal
          profit.type = profitTypeEnum.consume
          profitList.push(profit)
        })
        await this.profitRespository.createQueryBuilder(null, queryRunner).insert().into(Profit).values(profitList).execute()
        await WXAPIOBJ.clearPayWallet(findAnswer.wx_user)
      }

      await queryRunner.commitTransaction()
      await queryRunner.release();

      noticeList.map(e => {
        this.wsStartGateway.postUpdateNotice(e.wx_user)
      })
      this.wsStartGateway.postUpdateVideo(video_id)
    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }

  async rejectAnswer(answer_id: number, user_token:number, reject_reason: number): Promise<any> {
    let findWxUser = await this.userRespository.findOne({where:{id: user_token}});
    if(!findWxUser){
      return '用户不存在'
    }
    //查询视频/图片
    let findAnswer = await this.asRepository.findOne({where:{id: answer_id}})
    if(!findAnswer){
      return '答案不存在'
    }
    let db: DataBase = new DataBase()
    let connection = await db.getConnection()
    const queryRunner = connection.createQueryRunner()
    await queryRunner.connect()
    // 开始事务
    await queryRunner.startTransaction()
    try {
      let noticeList = []
      //你的回答被拒绝
      let notice = new Notices()
      notice.create_time = new Date()
      notice.video_id = findAnswer.video_id
      notice.wx_user = findAnswer.wx_user
      notice.check = NoticeCheckEnum.no
      notice.type = NoticeTypeEnum.answer_reject
      notice.answer_id = answer_id
      notice.reject_reason = reject_reason
      noticeList.push(notice)

      //保存通知
      await this.noticesRepository.createQueryBuilder(null,queryRunner)
        .insert()
        .into(Notices)
        .values(noticeList)
        .execute()
      //修改当前答案审核状态为未通过
      await this.asRepository.createQueryBuilder(null,queryRunner)
        .update({check:0,check_time:new Date(), reject_reason: reject_reason})
        .where({id: answer_id}).execute()

      await queryRunner.commitTransaction()
      await queryRunner.release();
      noticeList.map(e => {
        this.wsStartGateway.postUpdateNotice(e.wx_user)
      })
      this.wsStartGateway.postUpdateVideo(findAnswer.video_id)

    } catch (err) {
      // 有错误做出回滚更改
      await queryRunner.rollbackTransaction()
      await queryRunner.release();
      return err
    }
  }
}
